import { wechatBind, wechatLogin, wechatOauthLogin, wechatUnbind } from '@/api/third'
import { setStorageCache } from '@/common/cache'
import Helper from '@/common/helper'
import $wxsdk from '@/common/libs/sdk-h5-weixin'
import $store from '@/store'

// 加载微信公众号JSSDK
async function load() {
  if ($store.getters.platform.autoLogin && !$store.getters.isLogin && location.href.search('pages/common/redirect') === -1) {
    // 发起自动登陆
    // login()
  }
  // $wxsdk.init()
}

// 微信公众号登陆
async function login(code = '') {
  // 获取登陆地址
  if (!code) {
    const loginResult = await getLoginUrl()
    console.log('🚀 ~ login ~ loginResult:', loginResult)
    if (loginResult.errcode === 0 && loginResult.data.login_url) {
      setStorageCache('redirectUrl', location.href)
      window.location = loginResult.data.login_url
    }
  } else {
    // 解密code发起登陆
    const loginResult = await loginByCode(code)
    if (loginResult.error === 0) {
      return loginResult
    }
  }
  return false
}

// 微信公众号绑定
async function bind(code = '') {
  // 获取绑定地址
  if (code === '') {
    const loginResult = await getLoginUrl('bind')
    if (loginResult.error === 0 && loginResult.data.login_url) {
      setStorageCache('redirectUrl', location.href)
      window.location = loginResult.data.login_url
    }
  } else {
    // 解密code发起登陆
    const loginResult = await bindByCode(code)
    if (loginResult.error === 0) {
      return loginResult
    }
  }
  return false
}

// 微信公众号解除绑定
async function unbind() {
  const { error } = await wechatUnbind({
    platform: 'officialAccount',
  })
  return Promise.resolve(!error)
}

// 获取公众号登陆地址
/**
 * @param event 'login' | 'bind'
 * @param scope 'snsapi_base': 静默授权；'snsapi_userinfo'：主动授权
 */
function getLoginUrl(event = 'login', scope = 'snsapi_base') {
  let page = Helper.getRootUrl() + 'pages/common/redirect'
  // 前台构造请求 授权回调
  return new Promise((resolve, reject) => {
    resolve({
      errcode: 0,
      data: {
        login_url: `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6737c283b7cdaa8f&redirect_uri=${encodeURIComponent(page)}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`,
      },
      mag: '',
    })
  })

  // 后端接口构造请求 授权回调
  // return wechatOauthLogin({
  //   platform: 'officialAccount',
  //   payload: encodeURIComponent(
  //     JSON.stringify({
  //       page,
  //       event,
  //     }),
  //   ),
  // })
}

// 此处使用前端发送code在后端解密，防止用户在后端过长时间停留
function loginByCode(code) {
  return wechatLogin({
    platform: 'officialAccount',
    payload: encodeURIComponent(
      JSON.stringify({
        code,
      }),
    ),
  })
}

// 此处使用前端发送code在后端解密，防止用户在后端过长时间停留
function bindByCode(code) {
  return wechatBind({
    platform: 'officialAccount',
    payload: encodeURIComponent(
      JSON.stringify({
        code,
      }),
    ),
  })
}

export default {
  load,
  login,
  bind,
  unbind,
  jssdk: $wxsdk,
}
